package ca.llsutherland.squash.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.squash.domain.Administrator;
import ca.llsutherland.squash.domain.Clock;
import ca.llsutherland.squash.domain.Racquet;
import ca.llsutherland.squash.domain.helper.RacquetsHelper;
import ca.llsutherland.squash.exceptions.ValidationException;
import ca.llsutherland.squash.utils.StringUtils;

public class RacquetsDao extends BaseDao {

    private static RacquetsDao instance = new RacquetsDao();

    @Override
    public String getUnderlyingTableName() {
        return "RACQUETS";
    }

    public static RacquetsDao getInstance() {
        return instance ;
    }

    public Racquet create(Racquet racquet) {
        
        String sql = "INSERT INTO " + getUnderlyingTableName() + " (BRAND, MODEL, DATE_CREATED, DATE_UPDATED, ADMINISTRATOR_ID) VALUES ("
            + StringUtils.addSingleQuotes(racquet.getBrand()) + ", "
            + StringUtils.addSingleQuotes(racquet.getModel()) + ", "
            + StringUtils.addSingleQuotes(racquet.getDateCreated().toString()) + ", "
            + StringUtils.addSingleQuotes(racquet.getDateUpdated().toString()) + ", "
            + racquet.getCreatedBy().getId() + ")";
        Long lastInsertedId = super.create(sql);
        return findById(lastInsertedId);
    }

    private Racquet findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildRacquet(findByIdQuery);
    }

    private Racquet buildRacquet(String sql) {
        Racquet racquet = null;
        ResultSet rs = super.findByQuery(sql);
        try {
            if(rs.next()){
                String brand = rs.getString("BRAND");
                Clock dateCreated = new Clock(rs.getTimestamp("DATE_CREATED").getTime());
                Clock dateUpdated = new Clock(rs.getTimestamp("DATE_UPDATED").getTime());
                String model = rs.getString("MODEL");
                Long id = Long.valueOf(rs.getLong("ID"));
                Administrator createdBy = AdministratorsDao.getInstance().findById(rs.getLong("ADMINISTRATOR_ID"));
                racquet = RacquetsHelper.createNewRacquet(brand, model, dateCreated, dateUpdated, createdBy, id);
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildRacquet()");
        } finally {
            rs = null;            
        }
        return racquet;
    }
}
